package com.qfedu.aunt.commons.manager;

import com.qfedu.aunt.commons.constance.Constance;
import com.qfedu.aunt.commons.exception.BusinessException;
import com.qfedu.aunt.commons.result.ResponseCode;
import com.qfedu.aunt.commons.utils.ExceptionUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.stereotype.Component;


/**
 * @author xiaobobo
 * @title: SmsManager
 * @projectName aunt_commons_2209
 * @description: TODO
 * @date 2022/10/26  14:40
 */
@Component
@Slf4j
public class SmsManager {

    /**
     * 发送短信的程序
     * @param telPhoneNumber：电话号码
     * @param code1：验证码
     */
    public void sendSms(String telPhoneNumber,int code1){
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(Constance.getUrl());

        client.getParams().setContentCharset("GBK");
        method.setRequestHeader("ContentType","application/x-www-form-urlencoded;charset=GBK");

        String content = new String("您的验证码是：" + code1 + "。请不要把验证码泄露给其他人。");
        NameValuePair[] data = {//提交短信
                new NameValuePair("account", "C88747695"), //查看用户名是登录用户中心->验证码短信->产品总览->APIID
                new NameValuePair("password", "8e2c707b79765491a4a2114eec0fdb9d"),  //查看密码请登录用户中心->验证码短信->产品总览->APIKEY
                //new NameValuePair("password", util.StringUtil.MD5Encode("密码")),
                new NameValuePair("mobile", telPhoneNumber),
                new NameValuePair("content", content),
        };
        method.setRequestBody(data);
        try {
            client.executeMethod(method);
            String SubmitResult =method.getResponseBodyAsString();
            Document doc = DocumentHelper.parseText(SubmitResult);
            Element root = doc.getRootElement();
            String code = root.elementText("code");
            if("2".equals(code)){
                System.out.println("短信提交成功");
                log.info("短信发送成功:{}",telPhoneNumber);
            }

        } catch (Exception e) {
            //e.printStackTrace();
            log.info("短信发送失败:{}---信息是:{}",telPhoneNumber, ExceptionUtils.getMessage(e));
            throw new BusinessException(
                    ResponseCode.SEND_SMS_ERROR.getCode(),
                    ResponseCode.SEND_SMS_ERROR.getMessage());
        }
    }


}
